//
//  GZLoginController.swift
//  GZMarathon
//
//  Created by apple on 2021/10/19.
//

import UIKit
import SVProgressHUD
import SnapKit
class GZLoginController: EBBaseViewController {
    
    @IBOutlet weak var rememberBt: UIButton!
    @IBOutlet weak var subBt: UIButton!
    @IBOutlet weak var verificationTF: UITextField!
    @IBOutlet weak var pdTF: UITextField!
    @IBOutlet weak var nameTF: UITextField!
    
    @IBOutlet weak var verficationView: UIView!
    

    
    var captchaView:UIImageView?
    
    var capData:CaptchaModel?

    
    override func viewDidLoad() {
  
        super.viewDidLoad()

        
        nameTF.delegate = self
        pdTF.delegate = self
        verificationTF.delegate = self

        getData()
        
        bindUserName()

    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = false
    }
    
   func getData(){
        ApiProvider.request(EBAPI.captcha, model: CaptchaModel.self) { [self] model, isSuccess in

            if(isSuccess == true){
                self.capData = model
                self.setUI()
                print("\(model?.data?.captcha_image ?? "")")
            }
            
            
        }
    }
    
    
    func setUI(){
//公网账号
//        急救人员 18888888885 / eb823258
//        急救人员 18888888886 / eb823258
//        驾驶员 17777777771 / eb823258
//        驾驶员 17777777772 / eb823258
//        防疫人员 17666666661 / eb823258
//        防疫人员 17666666662 / eb823258
        
        
        //内网账号
        //广马-防疫人员：13999999993 / eb823258
        //广马-急救人员：13999999991 / eb823258
        //广马-驾驶员：13999999992 / eb823258
        
//        self.nameTF.text = "13999999991"
//        self.pdTF.text = "eb823258"
        
        rememberBt.semanticContentAttribute = .forceRightToLeft
        
        let leftview = UIImageView(image: UIImage(named: "icon_denglu_yonghuming"))
        leftview.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
        nameTF.leftViewMode = UITextField.ViewMode.always
        nameTF.leftView = leftview
        
        let leftview1 = UIImageView(image: UIImage(named: "icon_denglu_mima"))
        leftview1.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
        pdTF.leftViewMode = UITextField.ViewMode.always
        pdTF.leftView = leftview1
        
        let leftview2 = UIImageView(image: UIImage(named: "icon_denglu_yanzhengma"))
        leftview2.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
        verificationTF.leftViewMode = UITextField.ViewMode.always
        verificationTF.leftView = leftview2
        
        
        let rightView = UIButton(type: .custom)
//        rightView.isSelected = true
        rightView.setImage(UIImage(named: "icon_denglu_yincang"), for: .normal)
        rightView.setImage(UIImage(named: "icon_denglu_xianshi"), for: .selected)

        rightView.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
        pdTF.rightViewMode = UITextField.ViewMode.always
        pdTF.rightView = rightView

//        rightView.addTarget(self, action: #selector(clickEyeBtn(bt:)), for: .touchUpInside)
        
        let base64String = (capData?.data?.captcha_image)!.replacingOccurrences(of: "data:image/png;base64,", with: "")
                            
        //转换尝试判断，有可能返回的数据丢失"=="，如果丢失，swift校验不通过
        var imageData = Data(base64Encoded: base64String, options: .ignoreUnknownCharacters)
        if imageData == nil {
            imageData = Data(base64Encoded: base64String + "==", options: .ignoreUnknownCharacters) //如果数据不正确，添加"=="重试
        }

        rightView.addTarget(self, action: #selector(clickEyeBtn(sender:)), for: .touchUpInside)

        
        captchaView = UIImageView()
        captchaView?.isUserInteractionEnabled = true
        captchaView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(getPic)))
        verficationView.addSubview(captchaView!)
        captchaView?.snp.makeConstraints { make in
            make.top.bottom.left.right.equalToSuperview()
        }

  
        if let data = imageData {
            captchaView?.image = UIImage(data: data)
        }
        
        let login = UserDefaults.standard.object(forKey: "ISLOGOIN")
        if(login != nil){
            rememberBt.isSelected = true
        }
   
    }

    @objc func getPic(){
        ApiProvider.request(EBAPI.captcha, model: CaptchaModel.self) { [self] model, isSuccess in

            self.capData = model
            self.changePic()
            
        }
    }
    
    func changePic(){
        
        let base64String = (capData?.data?.captcha_image)!.replacingOccurrences(of: "data:image/png;base64,", with: "")
                            
        //转换尝试判断，有可能返回的数据丢失"=="，如果丢失，swift校验不通过
        var imageData = Data(base64Encoded: base64String, options: .ignoreUnknownCharacters)
        if imageData == nil {
            imageData = Data(base64Encoded: base64String + "==", options: .ignoreUnknownCharacters) //如果数据不正确，添加"=="重试
        }
        
        if let data = imageData {
            captchaView?.image = UIImage(data: data)
        }

    }

    @objc func clickEyeBtn(sender: UIButton){
        sender.isSelected = !sender.isSelected

        pdTF.isSecureTextEntry = !pdTF.isSecureTextEntry
    }

    @IBAction func clickLogin(_ sender: Any) {
        login()
    }
    
    @IBAction func forgetClick(_ sender: Any) {
        
        let vc = UIStoryboard(name: "GM", bundle: nil).instantiateViewController(withIdentifier: "GZResetPasswordOneViewController") as! GZResetPasswordOneViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func rememberClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected

    }
    
    
    @IBAction func userClick(_ sender: Any) {
    }
    
    
    @IBAction func supportClick(_ sender: Any) {
    }
    
    func login()  {
        
        view.endEditing(true)

        if nameTF.text?.count == 0 {
            SVProgressHUD.showError(withStatus: "请输入用户名")
            return
        }

        if pdTF.text?.count == 0 {
            SVProgressHUD.showError(withStatus: "请输入密码")
            return
        }

        
        if verificationTF.text?.count == 0 {
            SVProgressHUD.showError(withStatus: "请输入验证码")
            return
        }
        
        
        

        
        SVProgressHUD.show()
        //广马-防疫人员：13999999993 / eb823258
        //广马-急救人员：13999999991 /d eb823258
        //广马-驾驶员：13999999992 / eb823258
        
        SVProgressHUD.show()
        ApiProvider.request(EBAPI.userLogin(username: nameTF.text ?? "", password: pdTF.text ?? "",captcha_id: capData?.data?.captcha_id ?? "" ,captcha: verificationTF.text ?? ""), model: GZUserLogin.self) { model, isSuccess in

            SVProgressHUD.dismiss()

            guard let result = model else{
                SVProgressHUD.showError(withStatus: "登录失败")
                return
            }

            if result.code != "200"{
                SVProgressHUD.showError(withStatus: result.message)
                return
            }
            self.confUserName()
            GZCurrentUser.shared.currentUser = result.data

            appdelegate().showMainTabbar(type: result.data.account_type)
            

        }
   
    }

}


extension GZLoginController:UITextFieldDelegate{
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        if((nameTF.text?.count != 0) && (verificationTF.text?.count != 0) && (pdTF.text?.count != 0)){
            subBt.backgroundColor = UIColor("#2E4BF4")
            subBt.isUserInteractionEnabled = true
        }else{
            subBt.isUserInteractionEnabled = false
            subBt.backgroundColor = UIColor("#C1C9FC")

        }
    }
    
    
    func confUserName(){
        if rememberBt.isSelected {
            UserDefaults.standard.setValue(nameTF.text!, forKey: "k_user_name")
            UserDefaults.standard.setValue(pdTF.text!, forKey: "k_user_psw")
            UserDefaults.standard.setValue(true, forKey: "k_is_remember")
        }else{
            UserDefaults.standard.setValue(false, forKey: "k_is_remember")
        }
        UserDefaults.standard.synchronize()
    }
    
    func bindUserName(){
        let isRemember = UserDefaults.standard.bool(forKey: "k_is_remember")
        rememberBt.isSelected = isRemember
        if isRemember == true{
            let uname = UserDefaults.standard.string(forKey: "k_user_name")
            let psw = UserDefaults.standard.string(forKey: "k_user_psw")
            nameTF.text = uname
            pdTF.text = psw

        }
    }
    
}
